<template>
  <div id="bool">
    <van-nav-bar title="血液指标" left-text="返回" left-arrow @click-left="back" fixed placeholder/>
    <div class="main">
      <div class="content">
        <van-form :show-error-message="false" label-width="130px" ref="vanForm">
          <van-row type="flex" justify="space-between" align="center">
            <van-col span="21"
              ><van-field
                v-model="form.xueye_na"
                label="钠"
                placeholder="请输入"
                type="number"
                maxlength="6"
                :rules="[{ required: true, message: '请输入钠' }]"
            /></van-col>
            <van-col span="5" :offset="1" class="company">mmol/L</van-col>
          </van-row>
          <van-row type="flex" justify="space-between" align="center">
            <van-col span="21"
              ><van-field
                v-model="form.xueye_gai"
                label="钙"
                placeholder="请输入"
                type="number"
                maxlength="6"
                :rules="[{ required: true, message: '请输入钙' }]"
            /></van-col>
            <van-col span="5" :offset="1" class="company">mmol/L</van-col>
          </van-row>
          <van-row type="flex" justify="space-between" align="center">
            <van-col span="21"
              ><van-field
                v-model="form.xueye_jia"
                label="钾"
                placeholder="请输入"
                type="number"
                maxlength="6"
                :rules="[{ required: true, message: '请输入钾' }]"
            /></van-col>
            <van-col span="5" :offset="1" class="company">mmol/L</van-col>
          </van-row>
          <van-row type="flex" justify="space-between" align="center">
            <van-col span="21"
              ><van-field
                v-model="form.xueye_lin"
                label="磷"
                placeholder="请输入"
                type="number"
                maxlength="6"
                :rules="[{ required: true, message: '请输入磷' }]"
            /></van-col>
            <van-col span="5" :offset="1" class="company">mmol/L</van-col>
          </van-row>
          <van-row type="flex" justify="space-between" align="center">
            <van-col span="21"
              ><van-field
                v-model="form.xueye_crp"
                label="C反应蛋白（CRP）"
                placeholder="请输入"
                type="number"
                maxlength="6"
                :rules="[{ required: true, message: '请输入C反应蛋白（CRP）' }]"
            /></van-col>
            <van-col span="5" :offset="1" class="company">mg/DL</van-col>
          </van-row>
          <van-row type="flex" justify="space-between" align="center">
            <van-col span="21"
              ><van-field
                v-model="form.xueye_tbil"
                label="总胆红素（TBIL）"
                placeholder="请输入"
                type="number"
                maxlength="6"
                :rules="[{ required: true, message: '请输入总胆红素（TBIL）' }]"
            /></van-col>
            <van-col span="5" :offset="1" class="company">umd/L</van-col>
          </van-row>
          <van-row type="flex" justify="space-between" align="center">
            <van-col span="21"
              ><van-field
                v-model="form.xueye_alb"
                label="白蛋白（ALB）"
                placeholder="请输入"
                type="number"
                maxlength="6"
                :rules="[{ required: true, message: '请输入白蛋白（ALB）' }]"
            /></van-col>
            <van-col span="5" :offset="1" class="company">g/L</van-col>
          </van-row>
          <van-row type="flex" justify="space-between" align="center">
            <van-col span="21"
              ><van-field
                v-model="form.xueye_alt"
                label="谷丙转氨酶（ALT）"
                placeholder="请输入"
                type="number"
                maxlength="6"
                :rules="[{ required: true, message: '请输入白蛋白（ALB）' }]"
            /></van-col>
            <van-col span="5" :offset="1" class="company">u/L</van-col>
          </van-row>
          <van-row type="flex" justify="space-between" align="center">
            <van-col span="21"
              ><van-field
                v-model="form.xueye_cr"
                label="肌酐（Cr）"
                placeholder="请输入"
                type="number"
                maxlength="6"
                :rules="[{ required: true, message: '请输入白蛋白（ALB）' }]"
            /></van-col>
            <van-col span="5" :offset="1" class="company">umd/L</van-col>
          </van-row>
        </van-form>
      </div>
      <div class="upload">
        <!-- upload.png -->
        <van-uploader
        multiple
          style="display:block"
          :after-read="afterRead"
          v-model="fileList"
          :before-read="beforeRead"
          :before-delete="deleteImg"
        >
          <img src="@/assets/images/upload.png" alt="" class="uploadImg" />
        </van-uploader>
      </div>
      <div class="save">
        <van-button round type="info" :disabled="disabled" @click="save">保存并提交</van-button>
      </div>
    </div>
  </div>
</template>

<script>
import { upFiles, addMedia } from "@/apis/journal";
import { addHealthLog } from "@/apis/journal";
import apiConfig from "../../../config/api.config";
// 图片压缩
import { uploadImgs } from "../../../config/upload"
export default {
  data() {
    return {
      uploadImgs,
      apiConfig,
      disabled:false,
      form: {
        hzid:null,
        part: 4,
        xueye_na: "",
        xueye_gai: "",
        xueye_jia: "",
        xueye_lin: "",
        xueye_crp: "",
        xueye_tbil: "",
        xueye_alb: "",
        xueye_alt: "",
        xueye_cr: "",
        xueye_img: []
      },
      fileList: [],
      date:''
    };
  },
  methods: {
    back() {
      this.$router.go(-1); //返回上一层
    },
    getnewDate() {
      var myDate = new Date();
      var time = myDate
        .toLocaleDateString()
        .split("/")
        .join("-");
        this.date = time;
    },
    beforeRead(file) {
      console.log(file)
      if (
        file.type !== "image/jpeg" &&
        file.type !== "image/jpg" &&
        file.type !== "image/gif" &&
        file.type !== "image/png"
      ) {
        this.$toast("请上传 .jpg，.png，.gif 格式图片");
        return false;
      }
      return true;
    },
    afterRead(file) {
      // 此时可以自行将文件上传至服务器
      file.status = 'uploading';
      file.message = '上传中...';
      this.disabled = true
      this.uploadImgs(file)
      setTimeout(()=>{
          if( sessionStorage.getItem('base64') != '' && sessionStorage.getItem('base64')!=null){
          upFiles({file:sessionStorage.getItem('base64')})
            .then(res => {
            if(res.codes == "200"){
                this.form.xueye_img.push(res.data);
                file.status = '';
                file.message = '';
                this.disabled = false
            }else{
              file.status = 'failed';
              file.message = '上传失败';
              this.disabled = false
            }
            })
            .catch(err => {
              this.disabled = false
              file.status = 'failed';
              file.message = '上传失败';
              this.$toast("上传失败");
              
            });
          sessionStorage.removeItem('base64')
        }else{
          file.status = 'failed';
          file.message = '上传失败';
          this.$toast("上传失败");
        }
        },1600)

      // upFiles(file)
      //   .then(res => {
      //    if(res.codes == "200"){
      //       let arr = res.data;
      //       arr.forEach(item => {
      //         this.form.xueye_img.push(item);
      //       });
      //       file.status = '';
      //       file.message = '';
      //       this.disabled = false
      //    }else{
      //     file.status = 'failed';
      //     file.message = '上传失败';
      //     this.disabled = false
      //    }
      //   })
      //   .catch(err => {
      //     this.disabled = false
      //     file.status = 'failed';
      //     file.message = '上传失败';
      //     this.$toast("上传失败");
          
      //   });
    },
    save() {
      this.form.action='add'
      // 复康日志版本
      this.form.yemian = apiConfig.journal
      addHealthLog(this.form)
        .then(res => {
          this.$toast("添加成功");
          this.$router.go(-1);
          // this.form.id = res.data.id;
          let expire = new Date(
            new Date().setDate(new Date().getDate() + 1)
          ).setHours(0, 0, 0, 0);
          this.localStorageSet("id", res.data.id, expire);
          // this.localStorageSet("bool", this.form, expire);
        })
        .catch(err => {
          if(err.msg){
            this.$toast(err.msg);
          }else{
            this.$toast("网络错误"); 
          }
        });
    },
    deleteImg(detail,$event) {
      console.log($event)
      this.fileList.forEach((item,index) =>{
        if($event.index == index){
          this.fileList.splice(index,1)
          this.form.xueye_img.splice(index,1)
        }
      })
    }
  },
  mounted() {
    let id = this.localStorageGet("id");
    // let detail = this.localStorageGet("bool");
    if (id) {
      this.form.id = id;
    }
    // if (detail) {
    //   this.form = detail || {
    //     part: 4,
    //     xueye_na: "",
    //     xueye_gai: "",
    //     xueye_jia: "",
    //     xueye_lin: "",
    //     xueye_crp: "",
    //     xueye_tbil: "",
    //     xueye_alb: "",
    //     xueye_alt: "",
    //     xueye_cr: "",
    //     xueye_img: []
    //   };
    //   this.form.xueye_img.forEach(item=>{
    //     item = apiConfig.baseUrl + item.replace(/\\/g, "/");
    //     this.fileList.push({url:item});
    //   })
    // }
    this.getnewDate()
    let log_date = localStorage.getItem('log_date')
    // if( log_date == this.date ){
      addHealthLog({action:'list',id:id,hzid:this.form.hzid})
       .then(ress=>{
        if(ress.codes == 200){
          console.log(ress)  
          var arr = ress.data.list
          for(var key in this.form){
            for(var val in arr){
              if(key == val){
              if(arr[val] !== ' '){
                  this.form[key] = arr[key]
                }
              }
            }

           }
           if(this.form.xueye_img == null){
             this.form.xueye_img =[]
           }
            this.form.xueye_img.forEach(item=>{
              item = apiConfig.imgUrl + item.replace(/\\/g, "/");
              this.fileList.push({url:item});
            })
          }
      
        })
    // }
  },
  created() {
     this.form.hzid = this.$route.params.hzid
  },
};
</script>

<style lang="less">
#bool {
  .van-nav-bar{
    .van-icon,.van-nav-bar__text {
    color: #404040;
    }
  }
  .main {
    margin: 10px;
    .content {
      background-color: #fff;
    }
    .upload {
      margin-top: 10px;
      width: 355px;
      // height: 205px;
      background-color: #fff;
      padding: 53px 0 10px;
      .van-uploader,
      .van-uploader__input-wrapper,
      .uploadImg {
        width: 330px;
        // height: 125px;
        margin: auto;
      }
    }
    .save {
      margin-top: 50px;
      text-align: center;
      .van-button {
        width: 281px;
        height: 37px;
      }
    }
  }
}
</style>
